package com.xuhuan.practice;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;

/**
 * @author: huan.xu
 * @create: 2024/6/10 19:23
 * @description: jwt测试
 **/
public class JwtTerst {

  /**
   * 秘钥
   */
  private static String SECRET = "xuhuan";

  /**
   * 生成JWT
   */
  @Test
  public void testGenJWT() {
    Map<String, Object> chaims = new HashMap<>();
    chaims.put("id", 1);
    chaims.put("username", "xuhuan");
    String token = JWT.create()
        .withClaim("claims", chaims)
        .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 2))
        .sign(Algorithm.HMAC256(SECRET));
    System.out.println(token);
  }

  /**
   * 验证JWT
   */
  @Test
  public void testParseJWT() {
    String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
        + ".eyJ1c2VyIjp7ImlkIjoxLCJ1c2VybmFtZSI6IuW8oOS4iSJ9LCJleHAiOjE3MTgwMjYxMjN9"
        + ".2roWdJvMFjxV_LTQBZibgV79beiSXc3KFOcIaxtXNDk";
    JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
    DecodedJWT decodedJWT = jwtVerifier.verify(token);
    Map<String, Claim> claims = decodedJWT.getClaims();
    System.out.println(claims.get("claims"));
  }
}
